import React, { useEffect } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Box, Grid, GridItem, Input, NumberInput, Text } from '@nova-hf/ui';
import { useTranslation } from 'beta/utils/i18n';
import { useRouter } from 'next/router';
import { useServiceUserQuery } from 'typings/graphql';

import { StillingarLoader } from '../components/StillingarLoader';

type UserSettingsForm = {
  nationalId: string;
  email: string;
  name: string;
};

export const UserInfoSettingsContainer = () => {
  const { query } = useRouter();
  const { t } = useTranslation('stillingar');

  const { control, setValue } = useForm<UserSettingsForm>({
    defaultValues: {
      nationalId: '',
      name: '',
      email: '',
    },
    delayError: 500,
    mode: 'onChange',
  });

  const { data, loading, error } = useServiceUserQuery({
    variables: {
      serviceId: (query.serviceId as string) ?? '',
    },
  });

  const serviceUser = data?.service?.user;

  useEffect(() => {
    if (serviceUser?.id) {
      setValue('name', serviceUser?.name ?? '');
      setValue('nationalId', serviceUser?.nationalId ?? '');
      setValue('email', serviceUser?.email ?? '');
    }
  }, [serviceUser]);

  if (!serviceUser || error) return null;
  if (loading) return <StillingarLoader />;

  return (
    <Grid gridTemplate={{ sm: 4, md: 8 }}>
      <GridItem gridColumn={{ sm: 'span4', md: 'span7' }}>
        <Box marginBottom={[5]}>
          <Text variant="pMediumBold">{t('userSection.updateUserEyebrow')}</Text>
          <Text variant="pMediumRegular">{t('userSection.updateUserDescriptionFiber')}</Text>
        </Box>
      </GridItem>
      <GridItem gridColumn={{ sm: 'span4' }}>
        <Controller
          name="nationalId"
          control={control}
          render={({ field }) => {
            const { name, ...rest } = field;
            return (
              <NumberInput
                id="userNationalId"
                name={name}
                numberType="nationalId"
                label={t('userSection.nationalIdLabel')}
                disabled
                {...rest}
              />
            );
          }}
        />
      </GridItem>
      <GridItem gridColumn={{ sm: 'span4' }}>
        <Controller
          name="name"
          control={control}
          render={({ field }) => {
            const { name, ...rest } = field;
            return (
              <Input
                id="userName"
                name={name}
                label={t('userSection.nameLabel')}
                disabled
                {...rest}
              />
            );
          }}
        />
      </GridItem>
    </Grid>
  );
};
